from google.appengine.ext import webapp, gql
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db


from models import Business, Deal, User
import util
import tasks

import string
import logging
from BeautifulSoup import *
from string import atoi_error

##
#this file main role is to handle add request for business and deals in business
class DataBaseAddBusinessInfoHandler(webapp.RequestHandler):

    def get(self): 
        self.response.out.write(''' 
        <html> 
          <body> 
            <form method="post"> 
              <p>XML: <input type="string" name="xml" /></p>
              <p>User_name: <input type="string" name="user_name" /></p>
              <p>Email: <input type="string" name="email" /></p>
              <p><input type="submit" /></p>  
            </form> 
          </body> 
        </html> 
        ''') 
        
    def post(self):
        
        logging.info("Starting add requst")
        
        self.response.headers['Content-Type'] = 'text/xml'

        user_name = self.request.get("user_name", "")
        email = self.request.get("email", "")
        logging.debug("user_name = " + unicode(user_name) + ", email = " + unicode(email))
        
        result = util.validate_user_credit(user_name, email)
        if (not result):
            self.response.out.write(util.produce_result_xml("failed"))
            return
        
        #get the xml
        xml = self.request.get("xml", "")
        
        logging.debug("xml got:")
        logging.debug(unicode(xml))
        
        add_business_list(xml, user_name, email)
        self.response.out.write(util.produce_result_xml("success"))
        
        logging.info("Finish add requset")
        
def add_business_list(xml, user_name, email):
    #get all the businesses in the xml
    soup = BeautifulStoneSoup(xml)
    business_list = soup.findAll(name = "business", recursive = True)
    
    for business in business_list:
        add_business(unicode(business), user_name, email)
        

def add_business(xml, user_name, email):
    
    soup = BeautifulStoneSoup(xml)
    business_entity = soup.find(name = "entity", attrs = {"kind" : "Business"}, recursive = True)
    
    business = util.get_business_from_xml(unicode(business_entity))
    if (business == None): return
    
    logging.info("adding business")
    
    business._source_type = "user"
    business._source = email;
    util.lat_lon_lookup(business, "en")
    business.put()
    
    deal_lst = soup.findAll(name = "entity", attrs = {"kind" : "Deal"}, recursive = True)
    for deal in deal_lst:
        add_deal(unicode(deal), business, user_name, email)
    

def add_deal(deal_xml, business, user_name, email):
    #check if its an exist deal and get it if it is.
    deal = util.get_deal_from_xml(deal_xml)
    
    logging.info("adding deal")
    
    #connect to business
    deal.business_item = business
    deal._source_type = "user"
    deal._source = email
    util.deal_type_finder(business, deal)
    deal.put()

class DataBaseDeleteHandler(webapp.RequestHandler):

    def get(self): 
        self.response.out.write(''' 
        <html> 
          <body> 
            <form method="post"> 
              <p>XML: <input type="string" name="xml" /></p>
              <p>User_name: <input type="string" name="user_name" /></p>
              <p>Email: <input type="string" name="email" /></p>
              <p><input type="submit" /></p>  
            </form> 
          </body> 
        </html> 
        ''') 
        
    def post(self):
        
        logging.info("Starting delete requst")
        
        self.response.headers['Content-Type'] = 'text/xml'

        user_name = self.request.get("user_name", "")
        email = self.request.get("email", "")
        logging.debug("user_name = " + unicode(user_name) + ", email = " + unicode(email))
        
        #get the xml
        xml = self.request.get("xml", "")
        
        logging.debug("xml got:")
        logging.debug(unicode(xml))
        
        #validate user name
        deal = util.get_deal_from_xml(xml, produce_new = False, update_changes = False)
        if (deal == None):
            self.response.out.write(util.produce_result_xml("failed"))
            return
        
        if (deal._source != email):
            self.response.out.write(util.produce_result_xml("failed"))
            return
        db.delete(deal)
        self.response.out.write(util.produce_result_xml("success"))
        
    
        
application = webapp.WSGIApplication([('/database/add', DataBaseAddBusinessInfoHandler), ('/database/add/delete', DataBaseDeleteHandler)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
